/**
 * Copyright (c) 2010 icer He <icerhe@gmail.com>
 */
package com.icerhe.trigger.task;

import com.icerhe.trigger.Consts;
import com.icerhe.trigger.MultiSelectPreference;
import com.icerhe.trigger.R;
import com.icerhe.trigger.TaskHelper;
import com.icerhe.trigger.R.xml;

import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.util.Log;

/**
 * @author icer
 *
 */
public class AirplaneModeTaskSetting extends PreferenceActivity implements
		OnPreferenceChangeListener {
	
	private CheckBoxPreference taskEnabled;
	private EditTextPreference taskLable;
	private EditTextPreference taskDesc;
	
	private MultiSelectPreference taskMonth;
	private MultiSelectPreference taskDayOfMonth;
	private MultiSelectPreference taskDayOfWeek;
	private MultiSelectPreference taskHour;
	private MultiSelectPreference taskMinute;
	private CheckBoxPreference 	  taskByDow;
	
	private ListPreference     airplaneMode;
	
	private AirplaneModeTask task;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.airplane_task_setting);
		
		//取得或新建Task
		long taskId = getIntent().getLongExtra(CronTask.INTENT_TASK_ID, -1);
		if (taskId==-1) {//新建任务
			task = new AirplaneModeTask(this);
		} else {//取得已有任务
			task = (AirplaneModeTask)TaskHelper.getCronTaskById(this, taskId);
		}
		
		//取得各preference的引用并设定setOnPreferenceChangeListener
		taskEnabled = (CheckBoxPreference)findPreference("task_enabled");
		taskEnabled.setOnPreferenceChangeListener(this);
		taskLable = (EditTextPreference)findPreference("task_label");
		taskLable.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference arg0, Object arg1) {
				taskLable.setSummary((String)arg1);
				saveTaskAsync();
				return true;
			}
		});
		
		airplaneMode = (ListPreference)findPreference("airplane_mode");
		airplaneMode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference arg0, Object arg1) {
				int idx = airplaneMode.findIndexOfValue((String)arg1);
				String selectedMode = airplaneMode.getEntries()[idx].toString();
				airplaneMode.setSummary(selectedMode);
				saveTaskAsync();
				return true;
			}
		});
		
		taskMonth = (MultiSelectPreference)findPreference("task_month");
		taskMonth.setAllCheckedSummary(getText(R.string.every_months).toString());
		taskMonth.setOnPreferenceChangeListener(this);
		taskDayOfMonth = (MultiSelectPreference)findPreference("task_day_of_month");
		taskDayOfMonth.setAllCheckedSummary(getText(R.string.every_dayofmonth).toString());
		taskDayOfMonth.setOnPreferenceChangeListener(this);
		taskDayOfWeek = (MultiSelectPreference)findPreference("task_day_of_week");
		taskDayOfWeek.setAllCheckedSummary(getText(R.string.every_dayofweek).toString());
		taskDayOfWeek.setOnPreferenceChangeListener(this);
		taskHour = (MultiSelectPreference)findPreference("task_hour");
		taskHour.setAllCheckedSummary(getText(R.string.every_hours).toString());
		taskHour.setOnPreferenceChangeListener(this);
		taskMinute = (MultiSelectPreference)findPreference("task_minute");
		taskMinute.setAllCheckedSummary(getText(R.string.every_minutes).toString());
		taskMinute.setOnPreferenceChangeListener(this);
		taskByDow = (CheckBoxPreference)findPreference("task_bydow");
		taskByDow.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference arg0, Object arg1) {
				Boolean val = (Boolean)arg1;
				if (val) {
					taskDayOfWeek.setEnabled(true);
					taskDayOfMonth.setEnabled(false);
				} else {
					taskDayOfWeek.setEnabled(false);
					taskDayOfMonth.setEnabled(true);
				}
				saveTaskAsync();
				return true;
			}
		});
		
		updatePreference();
	}
	
	private void updatePreference() {
		//初始化UI
		taskEnabled.setChecked(task.isEnabled()?true:false);
		taskLable.setText(task.title);
		taskLable.setSummary(task.title);

		int idx = airplaneMode.findIndexOfValue(String.valueOf(task.getAirplaneMode()));
		airplaneMode.setValueIndex(idx);
		airplaneMode.setSummary(airplaneMode.getEntries()[idx]);
		
		taskMonth.setValue(task.months);
		taskDayOfMonth.setValue(task.daysOfMonth);
		taskDayOfWeek.setValue(task.daysOfWeek);
		taskHour.setValue(task.hours);
		taskMinute.setValue(task.minutes); 
		taskByDow.setChecked(task.isByDow());
		taskDayOfWeek.setEnabled(task.isByDow());
		taskDayOfMonth.setEnabled(!task.isByDow());
	}
	
	// 用于非同步更新preference
    private static final Handler handler = new Handler();

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		saveTaskAsync();
		return true;
	}
	
	private void saveTaskAsync() {
		handler.post(new Runnable() {
			public void run() {
				saveTask();
			}
		});
	}
	
	/**
	 * 获取各preference控件的值并保存到AlarmTask对象中
	 */
	private void  saveTask() {
		Log.d(Consts.TAG, "AAirplaneModeSetting saveTask");
		task.enabled = taskEnabled.isChecked()?1:0;
		task.title = taskLable.getText();

		task.description = airplaneMode.getSummary().toString();
		
		task.setAirplaneMode(Integer.parseInt(airplaneMode.getValue()));
		
		task.months = taskMonth.getValue();
		task.daysOfMonth = taskDayOfMonth.getValue();
		task.daysOfWeek = taskDayOfWeek.getValue();
		task.hours = taskHour.getValue();
		task.minutes = taskMinute.getValue();
		task.setByDow(taskByDow.isChecked());


		if (task.id>0) { 
			TaskHelper.updateTask(this, task);
		} else {
			int id = TaskHelper.addTask(this, task);
			task.id = id;
		}
	}

}
